/**
 * 
 */
package com.frame.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 
 * @author alex.lee at 2010-9-16 上午11:34:11
 *
 * desc：
 */
public class ClassUtils {

	private static Log logger = LogFactory.getLog(ClassUtils.class);

	/**
	 * 鑾峰彇绫诲悕
	 * 
	 * @param clazz
	 *            绫�
	 * @return
	 */
	public static String getClassName(Class<? extends Object> clazz) {
		if (clazz == null)
			return null;
		String classname = clazz.getName();
		return classname.substring(classname.lastIndexOf(".") + 1);
	}

	public static String getLowerCaseClassName(Class<? extends Object> clazz) {
		return getClassName(clazz).toLowerCase();
	}

	/**
	 * 鑾峰彇瀵硅薄绫诲悕
	 * 
	 * @param obj
	 * @return
	 */
	public static String getModelName(Object obj) {
		if (obj == null)
			return null;
		String classname = obj.getClass().getName();
		return classname.substring(classname.lastIndexOf(".") + 1);
	}

	public static String getLowerCaseModelName(Object obj) {
		return toLowerFirstCase(getModelName(obj));
	}

	public static String toLowerFirstCase(String modelName) {
		if (modelName == null || modelName.trim().equals(""))
			return modelName;
		if (modelName.length() > 1)
			return modelName.substring(0, 1).toLowerCase()
					+ modelName.substring(1);
		return modelName.toUpperCase();
	}

	public static String getLowerCaseModelName(List<Object> list) {
		if (list == null || list.size() == 0)
			return null;
		String classname = list.get(0).getClass().getName();
		return toLowerFirstCase(classname
				.substring(classname.lastIndexOf(".") + 1));
	}


	public static String[] upFirstString(String[] string) {
		String[] string2 = new String[string.length];
		int i = 0;
		for (String str : string) {
			String s1 = str.trim().substring(0, 1);
			String s2 = str.trim().substring(1, str.trim().length());
			string2[i] = s1.toUpperCase() + s2;
			i++;
		}
		return string2;
	}

	public static String upSignString(String sign, String str) {

		StringBuilder strRe = new StringBuilder();
		String[] strs = str.split(sign);

		for (String strSign : strs) {
			String s1 = strSign.trim().substring(0, 1);
			String s2 = strSign.trim().substring(1, strSign.trim().length());
			strRe.append(s1.toUpperCase()).append(s2);
		}
		return strRe.toString();
	}

	

	

	public static String upFirstString(String string) {
		return upSignString("_", string);
	}

	public static void set(Method method, Object bean, Object[] param) {
		try {
			method.invoke(bean, param);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	public static void setParameterToPOJO(Object bean,
			Class<Object> paramClass, String field, String value)
			throws SecurityException, NoSuchMethodException, ParseException {
		Method method = null;
		method = bean.getClass().getMethod("set" + ClassUtils.upFirstString(field),
				new Class[] { paramClass });

		if (paramClass.equals(String.class)) {
			ClassUtils.set(method, bean, new Object[] { value });
		} else if (paramClass.equals(int.class)
				|| paramClass.equals(Integer.class)) {
			int intvalue = Integer.parseInt(value);
			ClassUtils.set(method, bean, new Object[] { intvalue });
		} else if (paramClass.equals(float.class)
				|| paramClass.equals(Float.class)) {
			float fvalue = Float.parseFloat(value);
			ClassUtils.set(method, bean, new Object[] { fvalue });
		} else if (paramClass.equals(double.class)
				|| paramClass.equals(Double.class)) {
			double dvalue = Double.parseDouble(value);
			ClassUtils.set(method, bean, new Object[] { dvalue });
		} else if (paramClass.equals(long.class)
				|| paramClass.equals(Long.class)) {
			long lvalue = Long.parseLong(value);
			ClassUtils.set(method, bean, new Object[] { lvalue });
		} else if (paramClass.equals(Date.class)) {
			Date date = null;
			SimpleDateFormat sdf = null;
			if (value.length() > 11)
				sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
			else
				sdf = new SimpleDateFormat("yy-MM-dd");
			date = sdf.parse(value);
			ClassUtils.set(method, bean, new Object[] { date });
		}
	}

	public static String getRootPackage(String packageName) {
		String rootPackage = null;
		String[] key = { "dao", "service", "Impl", "controller", "model",
				"action","mybatis" };
		for (int i = 0; i < key.length; i++) {
			int location = 0;
			if ((location = packageName.indexOf(key[i])) > 0) {
				String tmpStr = packageName.substring(0, location);
				rootPackage = tmpStr.substring(0, packageName.lastIndexOf("."));
			}
		}
		return rootPackage;
	}

	public static String getRootPackage(String[] packageName) {
		String rootPackage = null;
		String[] key = { "dao", "service", "Impl", "controller", "model",
				"action","mybatis" };
		for (int i = 0; i < key.length; i++) {
			int location = 0;
			if ((location = packageName[0].indexOf(key[i])) > 0) {
				String tmpStr = packageName[0].substring(0, location);
				rootPackage = tmpStr.substring(0, packageName[0]
						.lastIndexOf("."));
				break;
			}
		}
		return rootPackage;
	}

	public static String changeFirstChar(String str, boolean up) {
		if (str == null || str.trim().equals(""))
			return str;
		String s1 = up ? str.trim().substring(0, 1).toUpperCase() : str.trim()
				.substring(0, 1).toLowerCase();
		String s2 = str.trim().substring(1, str.trim().length());
		return s1 + s2;
	}

	public static String getFieldFromTableName(String tableName) {
		if (tableName == null || tableName.trim().equals(""))
			return tableName;
		String str = ClassUtils.upSignString("_", tableName);
		return ClassUtils.changeFirstChar(str, false);
	}


	/*
	 * public static void main(String[] args) { String dateStr =
	 * "2006-12-06 17:49:00"; System.out.println(Utils.getStringToDate(dateStr,
	 * null)); }
	 */

	

	@SuppressWarnings("unchecked")
	public static boolean isIpUser(String key, Hashtable<String, Long> filter,
			int maxHashSize, long maxTimeSize) {
		boolean isSuccess = false;
		long now = System.currentTimeMillis();

		if (!filter.containsKey(key) || (now - filter.get(key) > maxTimeSize)) {
			filter.put(key, now);
			isSuccess = true;
		}

		if (filter.size() >= maxHashSize) {
			for (Enumeration e = filter.keys(); e.hasMoreElements();) {
				String name = (String) e.nextElement();
				Long value = filter.get(name);
				if (now - value > maxTimeSize)
					filter.remove(name);
			}
		}
		return isSuccess;
	}

	public static String[] getROrderChars(String str) {

		if (null == str) {
			return null;
		}

		str = str.trim();
		int j = str.length();
		String[] rC = new String[j];

		for (char tempC : str.toCharArray()) {
			rC[--j] = String.valueOf(tempC);
		}

		return rC;
	}

	public static Date getStringToDate(String dateStr, String dateFormat) {

		if (null == dateFormat) {
			dateFormat = "yyyy-MM-dd HH:mm:ss";
		}

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
		Date date = null;

		try {
			date = simpleDateFormat.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return date;
	}

	public static String getISOForYui(String s) {
		if (s == null)
			return s;

		String s2 = null;
		try {
			s2 = new String(s.getBytes("ISO8859_1"), "UTF-8");
			s2 = new String(s2.getBytes("GBK"), "ISO8859_1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s2;
	}

	// Stream杞寲鎴怱tring鐨勫嚱鏁�
	public static String inputStream2String(InputStream in) throws IOException {

		StringBuffer out = new StringBuffer();

		byte[] b = new byte[4096];

		for (int n; (n = in.read(b)) != -1;) {

			out.append(new String(b, 0, n));

		}

		return out.toString();

	}

	// 瑙ｆ瀽xml鍑芥暟
	public static String[] getXml(String xml, String title, String[] codename) {
		InputStream in = null;

		// System.out.println(xml);

		if (xml != null && !xml.equals("")) {

			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();

				DocumentBuilder db = dbf.newDocumentBuilder();

				in = new ByteArrayInputStream(xml.getBytes("GBK"));

				Document doc = db.parse(in);

				doc.normalize();

				NodeList nl;

				nl = doc.getElementsByTagName(title);

				int num2 = codename.length;

				if (nl != null && nl.getLength() != 0) {
					String[] str = new String[num2]; // 瑙ｆ瀽鍑虹殑鍐呭鏀惧湪str鏁扮粍閲�

					for (int j = 0; j < nl.getLength(); j++)

					{

						Node node1 = nl.item(j);

						for (int k = 0; k < num2; k++)

						{

							NodeList nl11 = ((Element) node1)
									.getElementsByTagName(codename[k]);

							if (nl11 != null && nl11.getLength() != 0)

							{

								Node node11 = nl11.item(0).getFirstChild();

								if (node11 != null)

								{

									str[k] = node11.getNodeValue().trim();

									if (str[k] == null) {

										str[k] = "";

									}

								} else {

									str[k] = "";

								}

							}

						}

					}
					return str;
				}
			}

			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	// 瑙ｆ瀽xml鍑芥暟
	public static String[] getLoginXml(String xml) {
		InputStream in = null;

		// System.out.println(xml);

		if (xml != null && !xml.equals("")) {

			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory
						.newInstance();

				DocumentBuilder db = dbf.newDocumentBuilder();

				in = new ByteArrayInputStream(xml.getBytes());

				Document doc = db.parse(in);

				doc.normalize();

				NodeList nl;

				nl = doc.getElementsByTagName("User");

				String[] codename = { "UserName", "UserPass", "UserMail" };

				int num2 = codename.length;

				if (nl != null && nl.getLength() != 0) {
					String[] str = new String[num2]; // 瑙ｆ瀽鍑虹殑鍐呭鏀惧湪str鏁扮粍閲�

					for (int j = 0; j < nl.getLength(); j++)

					{

						Node node1 = nl.item(j);

						for (int k = 0; k < num2; k++)

						{

							NodeList nl11 = ((Element) node1)
									.getElementsByTagName(codename[k]);

							if (nl11 != null && nl11.getLength() != 0)

							{

								Node node11 = nl11.item(0).getFirstChild();

								if (node11 != null)

								{

									str[k] = node11.getNodeValue().trim();

									if (str[k] == null) {

										str[k] = "";

									}

								} else {

									str[k] = "";

								}

							}

						}

					}
					return str;
				}
			}

			catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;

	}


	public static boolean isNotEmpty(String str) {
		return (str != null && !str.trim().equals(""));
	}

	public static boolean isEmpty(String str) {
		return (str == null || str.trim().equals(""));
	}
	
	public static boolean isZero(int str) {
		return str ==0;
	}

	/**
	 * 寰楀埌鏈潵鍑犲ぉ鐨勬湀-鏃ュ瓧绗︿覆
	 * 
	 * @param format
	 * @param next
	 * @param type
	 *            :1:"YYYY-MM-dd",2:"MM-dd"
	 * @return
	 */
	public static final String getNextDate(String format, int next, int type) {
		if (format == null || format.length() == 0) {
			format = "yyyy-MM-dd";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		long dayLong = 24 * 60 * 60 * 1000;

		String nextDate = null;
		nextDate = sdf.format(new Date().getTime() + next * dayLong);
		if (type == 1) {
			return nextDate;
		}
		return nextDate.substring(5);
	}

	/**
	 * 灏哅M-dd绫诲瀷鐨勫瓧绗︿覆杞垚涓枃鏄剧ず褰㈠紡
	 * 
	 * @param date
	 * @return
	 */
	public static final String getDateChinese(String date) {
		return date.replaceAll("-", "鏈�") + "鏃�";
	}

	/**
	 * 灏嗘棩鏈熷瓧绗︿覆杞崲鎴愭棩鏈熺被鍨�
	 * 
	 * @param text
	 * @param pattern
	 * @return
	 */
	public static java.util.Date text2Date(String text, String pattern) {
		SimpleDateFormat formatter = new SimpleDateFormat(pattern);
		Date date = null;
		try {
			date = formatter.parse(text);
		} catch (Exception e) {
		}
		return date;
	}

	/**
	 * 鑾峰彇涓や釜鏃堕棿涔嬮棿鐨勫ぉ鏁帮紝灏忔椂锛屽垎锛岀
	 * 
	 * @param bigDate
	 * @return
	 */
	public static int[] getBetweenDate(String bigDate) {
		if (bigDate == null)
			return null;

		Date date = ClassUtils.formartDateTime(bigDate);
		Long durTime = 0L;
		durTime = date.getTime() - System.currentTimeMillis();
		int[] days = new int[4];
		if (durTime <= 0) {
			return null;
		}
		days[0] = (int) (durTime / (1000 * 3600 * 24));
		days[1] = (int) (durTime - new Long(days[0] * (1000 * 3600 * 24)))
				/ (1000 * 3600);
		days[2] = (int) (durTime - new Long(days[0] * (1000 * 3600 * 24)
				+ days[1] * (1000 * 3600)))
				/ (1000 * 60);
		days[3] = (int) (durTime - new Long(days[0] * (1000 * 3600 * 24)
				+ days[1] * (1000 * 3600) + days[2] * (1000 * 60))) / 1000;
		return days;
	}

	/*
	 * public static void main(String[] args){ int[] day =
	 * Utils.getBetweenDate(Utils
	 * .text2Date("2009-09-10 00:00:00","yyyy-mm-dd hh:mm:ss")); for(int
	 * i=0;i<4;i++){ System.out.println(day[i]); } }
	 */

	public static SimpleDateFormat sdf1 = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss");
	public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

	public static Date formartDate(String date) {
		try {
			return sdf2.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Date formartDateTime(String date) {
		try {
			return sdf1.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 寰楀埌鏌愪釜瀵硅薄public 灞炴�т负null 鐨勬暟閲�
	 * 
	 * @param object
	 * @return
	 */
	public static int classFieldIsNullNum(Object object) {
		int num = 0;
		Field fields[] = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				System.out.println(field.getName());
				System.out.println ("field.isAccessible():"+field.isAccessible());
//				sysofield.setAccessible(true);
				if(field.isAccessible()){
					System.out.println(field.getName());
					System.out.println(field.get(object).getClass());
//					num++;
				}
//				&& (field.get(object) == null) {
//					
//				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		return num;
	}

	/**
	 * 寰楀埌涓や釜鏁扮殑鐧惧垎姣�
	 * @param p1
	 * @param p2
	 * @return
	 */
	public static String percent(double p1, double p2) {
		String str;
		double p3 = p1 / p2;
		NumberFormat nf = NumberFormat.getPercentInstance();
		nf.setMinimumFractionDigits(0);
		str = nf.format(p3);
		return str;
	}
	
	
	
	
	/**
	 * 寰楀埌瀹㈡埛绔疘P
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			try {
				ip = request.getRemoteAddr();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ip.split(",")[0].trim();
	} 
	/**
	 * 灏嗚緭鍏ユ祦杞寲鎴愬瓧绗︿覆
	 * @param is
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
		return	convertStreamToString(is,"gbk");
	}
	
	/**
	 * 灏嗚緭鍏ユ祦杞寲鎴愬瓧绗︿覆
	 * @param is
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String convertStreamToString(InputStream is,String code) throws UnsupportedEncodingException {
		if(isEmpty(code)){
			code = "gbk";
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(is,code));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) { 
				sb.append(line);
			}
		} catch (IOException e) {
			System.err.print(e.getMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				System.err.print(e.getMessage());
			}

		}
		return sb.toString();
	}
	
	/**
	 * 鑾峰緱闅忔満鍒楄〃
	 * @param num 闅忔満鏁伴噺
	 * @param fromList 浠庨偅涓垪琛ㄥ彇
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List getRandList(int num ,List fromList){
		List newList=new ArrayList();
		if(fromList.size()<=num){
		return fromList;
		}else {
			List randNumsList=getRandNum(num, fromList.size());
			for(int i=0;i<num;i++){
			newList.add(fromList.get((Integer)randNumsList.get(i)));
			}
		}
		return newList;
	}
	/**
	 * 闅忔満鑾峰彇鍑犱釜鏁板瓧
	 * @param num 鑾峰彇鍑犱釜
	 * @param size 浠庡灏戜腑鑾峰彇
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List getRandNum(int num ,int size){
		List list=new ArrayList();
		Random rand = new Random();
		int randNum = 1;
		for(int i=0;i<num;i++){
			boolean same=false;
			randNum = rand.nextInt(size);
			for(int j=0;j<list.size();j++){
				if(randNum==(Integer)list.get(j)){
					same=true;
				}
			}
			if(same==true){
				i--;
				continue;
			}
			list.add(randNum);
		}
		
		return list;
	}
	
}
